<template>
    <div class="login-background">
        <div class="login-main">
            <span class="title">{{ platformName }}</span>
            <div class="login-content">
                <div class="left-content">
                    <span class="left-title public-padding">{{
                abbreviation
            }}</span>
                    <el-form>
                        <el-row class="login-row" type="flex" justify="center">
                            <el-col>
                                <el-input class="longin-public" v-model="username" placeholder="请输入用户名"
                                    prefix-icon="el-icon-user" />
                            </el-col>
                        </el-row>
                        <el-row class="login-row" type="flex" justify="center">
                            <el-col>
                                <el-input class="longin-public" placeholder="请输入密码" @keyup.13.native="userLogin"
                                    v-model="password" prefix-icon="el-icon-lock" show-password />
                            </el-col>
                        </el-row>
                    </el-form>
                    <el-row class="login-row">
                        <el-col type="flex" justify="center">
                            <el-button :loading="isLoading" @click="userLogin"
                                class="longin-public login-button">登录</el-button>
                        </el-col>
                    </el-row>
                </div>
                <div class="right-content">
                    <div class="right-scroll" @click="handleClick($event)">
                        <vue-seamless-scroll :data="notices" :class-option="scrollClassOption">
                            <ul class="scroll-ui">
                                <li v-for="item in notices" :key="item.id" class="scroll-li" :id="item.id"
                                    style="display:flex;align-items:center;flex-wrap:wrap">
                                    <div class="right-scroll-time" :data-obj="JSON.stringify(item)">
                                        {{ item.createTime }}
                                    </div>
                                    <div class="right-scroll-content" :data-obj="JSON.stringify(item)">
                                        {{ item.title }}
                                    </div>
                                    <div class="right-scroll-content" :data-obj="JSON.stringify(item)">
                                        {{ item.summary }}
                                    </div>
                                </li>
                            </ul>
                        </vue-seamless-scroll>
                    </div>
                </div>
            </div>
            <div class="login-footer">
                <span>Copyright 2021-2025 上海爱可及医疗科技有限公司、宁波市科技园区明天医网科技有限公司</span>
            </div>
        </div>
        <el-dialog :visible.sync="isResetVisible" :title="resetMessage" :close-on-click-modal="false"
            :modal-append-to-body="false" append-to-body width="40%">
            <el-form label-width="80px" :model="resetForm" :rules="resetRule" ref="resetForm" @submit.native.prevent>
                <el-row class="reset-row">
                    <el-col :span="24">
                        <el-form-item label="身份证号" prop="pCardId">
                            <el-input placeholder="身份证号后四位" v-model="resetForm.pCardId"
                                @keyup.enter.native="loginResetset" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-button class="login-button longin-reset" @click="loginResetset"
                            :loading="isResetLoading">用户重置并登录</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>
        <el-dialog :visible.sync="noticeDialogVisible" width="50%">
            <el-row type="flex" justify="center">
                <h3>{{ notice.title }}</h3>
            </el-row>
            <el-row type="flex" justify="center">
                <span style="color: grey">发布者: {{ notice.userName }} 时间:
                    {{ notice.createTime }}</span>
            </el-row>
            <hr />
            <el-row type="flex" style="flex-direction: column">
                <div style="color: grey">摘要: {{ notice.summary }}</div>
                <div style="margin-top: 20px" v-html="notice.content"></div>
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment/moment';
import { isPromptLoginMessage } from '@/client/libs/util';
import _ from 'lodash';
import VueSeamlessScroll from 'vue-seamless-scroll';

export default {
    name: 'NewLogin',
    components: {
        VueSeamlessScroll,
    },
    data() {
        const checkNumber = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('不能为空'));
            }
            // const reg =
            //     /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
            // if (reg.test(value)) {
            //     return callback();
            // }
            return callback();
        };
        return {
            noticeDialogVisible: false,
            notice: {},
            isResetVisible: false,
            resetForm: { pCardId: '' },
            resetRule: {
                pCardId: [
                    // 身份证号码
                    {
                        type: 'number',
                        validator: checkNumber,
                        message: `请输入身份证号`,
                        trigger: 'blur',
                    },
                ],
            },
            isResetLoading: false,
            resetMessage:
                '帐号已经登录!请输入身份证号后四位重置,若重置失败,请联系管理员!',
            username: '',
            password: '',
            platformName: '',
            abbreviation: '',
            systemLogoUrl: '/images/logo-now.png',
            passwordStrength: false,
            notices: [],
            scrollClassOption: {
                // 轮播鼠标控制停止
                hoverStop: true,
                // 轮播速度
                step: 0.4,
                // 开始无缝滚动最小数据长度
                limitMoveNum: 1,
                direction: 1, // 0 往下 1 往上 2向左 3向右
                switchDisabledClass: 'NO',
            },
            isShowFrontPage: false,
            isLoading: false,
        };
    },
    methods: {
        handleClick(event) {
            let InfoAnync = JSON.parse(event.target.dataset.obj)
            this.showNotice(InfoAnync.id)
        },
        showNotice(id) {
            this.$axios({
                // 详见 axios 请求配置项
                method: 'GET',
                url: `/PROXY-Remote/notices/bare/${id}`
            }).then(
                res => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data)
                    }
                    // 请求成功
                    this.notice = res.data.data
                    this.notice.updateTime = moment(this.notice.updateTime).format('YYYY-MM-DD hh:mm:ss')
                    this.noticeDialogVisible = true
                },
                err => {
                    this.$message.info(`${err.response.data.message}`)
                }
            )
        },
        // 识别关键字以 PROXY- 开头
        async noticesRequest() {
            try {
                await this.$axios({
                    // 详见 axios 请求配置项
                    method: 'GET',
                    url: '/PROXY-Remote/notices/bare',
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    // 查询结果数据
                    this.notices = [];
                    result.data.forEach((t) => {
                        const item = {
                            id: t.id,
                            typeName: t.typeName,
                            createTime: moment(t.createTime).format(
                                'YYYY-MM-DD'
                            ),
                            title: t.title,
                            summary: t.summary,
                        };
                        this.notices.push(item);
                    });
                });
            } catch (e) {
                // 跳出
            }
        },
        async userLogin() {
            // 使用 try catch模式
            try {
                this.isLoading = true;
                let Base64 = require('js-base64').Base64;
                let _this = this;
                await this.$axios({
                    method: 'POST',
                    url: '/PROXY-Remote/login',
                    params: {
                        username: this.username,
                        password: Base64.encode(this.password),
                    },
                }).then((res) => {
                    this.isLoading = false;
                    // 请求失败
                    if (res.data.code !== 200) {
                        const message = res.data.message;
                        if (res.data.code === 500 && !res.data.data) {
                            if (message === '此账号不存在') {
                                _this.$message.warning(message);
                            } else if (message === '此账号已被冻结') {
                                _this.$message.warning(message);
                            } else if (message === '此账号已被删除') {
                                _this.$message.warning(message);
                            } else {
                                this.isResetVisible = true;
                            }
                            return;
                        }
                        if (isPromptLoginMessage(message, 'LOGIN')) {
                            _this.$message.warning(message);
                        }
                        return;
                    }
                    // 请求成功
                    const result = res.data.data;

                    const platform = {
                        name: '浦东医院病理平台',
                    };
                    let roleIds = [];
                    if (result.userInfo.roles) {
                        result.userInfo.roles.forEach((item) => {
                            roleIds.push(item.id);
                        });
                    }

                    const user = {
                        id: result.userInfo.id,
                        name: result.userInfo.name,
                        headImgUrl: result.userInfo.headUrl,
                        isDivisionConsultationApplyPermissions:
                            result.userInfo
                                .isDivisionConsultationApplyPermissions, //科内会诊申请权限
                        isOutsideConsultationApplyPermissions:
                            result.userInfo
                                .isOutsideConsultationApplyPermissions, //院外会诊申请权限
                        roleIds,
                    };
                    const permissionList = result['ui-item'];
                    console.log('permissionList-before', permissionList);
                    for (let init = 0; init < permissionList.length; init++) {
                        for (
                            let i = 0;
                            i < permissionList[init].permissionList.length;
                            i++
                        ) {
                            const iconString =
                                permissionList[init].permissionList[i].icon;
                            const [prefix, icon] = _.split(iconString, ' ');
                            permissionList[init].permissionList[i].prefix =
                                prefix;
                            permissionList[init].permissionList[i].icon = icon;
                        }
                    }
                    // 存储缓存数据
                    this.$store.commit('setPlatform', platform);
                    this.$store.commit('setPermissionList', permissionList);
                    this.$store.commit('loginTimeFlash');
                    //设置是否全屏
                    this.$store.commit('fullScreenChange', true);
                    // 设置登陆后的跳转页
                    this.$store.commit('setPropertyGeneral', {
                        key: 'nowRoute',
                        value: permissionList[0].permissionList[0].route,
                    });
                    this.$store.commit('setUser', user);

                    this.$router.push({
                        path: permissionList[0].permissionList[0].route,
                    });

                    this.$axios({
                        method: 'GET',
                        url: `/PROXY-Remote/institutions/${result.userInfo.institutionId}`,
                    }).then((res2) => {
                        console.log(res2);
                        if (res2 && res2.data.code === 200) {
                            const info = res2.data.data;
                            const institution = {
                                id: info.id,
                                isPlatform: info.isPlatform,
                                name: info.name,
                                isEnableTaskClaim: info.isEnableTaskClaim,
                            };
                            this.$store.commit('setInstitution', institution);
                        }
                    });
                });
            } catch (e) {
                if (isPromptLoginMessage(e.message, 'LOGIN')) {
                    this.$message.error(e.message);
                }
            }
        },
        async loginResetset() {
            console.log('1---------------------------------');
            let isValidate = false;
            this.$refs.resetForm.validate((valid) => {
                if (valid) {
                    isValidate = true;
                }
            });
            if (!isValidate) {
                return;
            }
            this.isResetLoading = true;
            await this.$axios({
                // 详见 axios 请求配置项
                method: 'GET',
                url: `/login/reset/token/card/id/${this.username}/${this.resetForm.pCardId}`,
            }).then((res) => {
                this.resetCount += 1;
                this.isResetVisible = false;
                // 请求失败
                if (res.data.code !== 200 || !res.data.data) {
                    const message = '重置登录失败，请联系管理员重置！！！';
                    if (isPromptLoginMessage(message, 'LOGIN')) {
                        this.$message.warning({ message });
                    }
                    return;
                }
                this.userLogin();
            });
            this.resetForm.pCardId = '';
            this.isResetLoading = false;
        },
        async getPlatform() {
            try {
                await this.$axios({
                    // 详见 axios 请求配置项
                    method: 'GET',
                    url: '/PROXY-Remote/institutions/platform',
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }
                    // 请求成功
                    const result = res.data.data;
                    this.platformName = result.name;
                    this.abbreviation = result.abbreviation;
                    this.systemLogoUrl = this.ImageServiceURL + result.logoUrl;
                    this.isShowFrontPage = result.isShowFrontPage;
                    if (this.isShowFrontPage === 'true') {
                        this.$router.push('/newLogin');
                    } else {
                        this.$router.push('/Login');
                    }
                });
            } catch (e) {
                // 跳出
            }
        },
    },
    computed: {
        isEworldSatus() { //是否是内嵌明天医网
            return this.$store.state.isEworld;
        },
    },
    mounted() {
        if(this.isEworldSatus){
            if( window.parent){
               window.parent.postMessage({ message: { from: 'aikeji', operate: 'loginOut' } }, '*')
            }  
        }else{
            this.$store.commit('stateInit');
            this.noticesRequest();
            this.getPlatform();
        }
       
    },
};
</script>

<style scoped>
.login-background {
    width: 100%;
    height: 100%;
    background: url('/images/bj.png');
    background-color: #ffffff;
}

.login-main {
    box-sizing: border-box;
    margin: 0 auto;
    width: 1065px;
    height: 100%;
    padding-top: 53px;
}

.title {
    font-size: 22px;
    display: inline-block;
    line-height: 40px;
    font-weight: 400;
    color: #ffffff;
    font-family: 'Microsoft YaHei', serif;
}

.login-content {
    margin-top: 53px;
    height: 548px;
    width: 1065px;
    border-radius: 16px;
    background-color: #469ce4;
}

.left-content {
    float: left;
    width: 400px;
    height: 528px;
    background: #fff;
    box-shadow: 0 2px 24px 0 rgba(0, 0, 0, .21);
    border-radius: 16px;
    margin: 10px;
}

.right-content {
    width: 642px;
    float: right;
    height: 100%;
    background-image: url('/images/login-pic.png');
}

.public-padding {
    width: 100%;
    text-align: center;
    padding-top: 85px;
}

.left-title {
    display: inline-block;
    font-size: 22px;
    font-family: 'Microsoft YaHei', serif;
    font-weight: 400;
    color: #0879d9;
    line-height: 40px;
}

.login-row {
    margin-top: 46px;
    margin-left: 40px;
}

.login-row /deep/ .longin-public {
    border-radius: 15px;
    min-height: 50px;
    width: 320px;
    height: 50px;
}

.reset-row /deep/ .longin-reset {
    margin-top: 12px;
    border-radius: 15px;
    min-height: 38px;
    width: 100%;
    height: 38px;
}

.login-button {
    background-color: #0879d9;
    color: white;
    border: #0879d9 1px;
}

.login-row>>>.el-input__inner {
    border-radius: 15px;
    min-height: 50px;
    width: 320px;
    height: 50px;
}

.login-footer {
    width: 100%;
    line-height: 40px;
    color: white;
    margin: 31px auto;
    font-size: 14px;
    text-align: center;
}

.right-scroll {
    margin-left: 100px;
    margin-top: 100px;
    height: 100px;
    width: 500px;
    overflow: hidden;
}

.scroll-ui {
    margin: 0;
}

.scroll-li {
    list-style-type: none;
    cursor: pointer;
    margin-top: 32px;
    margin-bottom: 0;
}

.right-scroll-time {
    font-size: 14px;
    color: black;
}

.right-scroll-content {
    font-size: 14px;
    color: #156bd8;
}

@media only screen and (max-width: 1000px) {
    .login-background[data-v-40ead59a] {
        background-size: cover;
        background-repeat: no-repeat;
    }

    .login-main {
        width: 533px;
        padding-top: 13px;
    }

    .login-content {
        width: 533px;
        height: 274px;
        margin-top: 3px
    }

    .left-title {
        font-size: 12px;
    }

    .public-padding {
        padding-top: 12px;
    }

    .left-content {
        width: 180px;
        height: 254px;
    }

    .right-content {
        width: 321px;
        background-size: cover;
    }

    .login-row .longin-public {
        width: 160px;
        height: 25px;
        min-height: 25px;
    }

    ::v-deep .login-row .el-input__inner {
        width: 160px;
        height: 25px;
        min-height: 25px;
    }

    ::v-deep .el-input__icon {
        line-height: 25px;
    }

    .login-row {
        margin-top: 25px;
        margin-left: 10px;
    }

    .login-button {
        padding: 0;
    }

    .right-scroll {
        margin-left: 50px;
        margin-top: 50px;
        width: 250px;
        height: 50px;
    }
}
</style>
